import {createRouter, createWebHistory} from 'vue-router'
import DynamicMenu from '../components/DynamicMenu.vue'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import OAuth2Callback from '../views/OAuth2Callback.vue'
import {useUserStore} from '../stores/user'
import {ElMessage} from 'element-plus'

const routes = [
    {
        path: '/',
        redirect: '/lz/study'
    },
    {
        path: '/lz/study',
        name: 'Home',
        component: Home,
        meta: {
            title: '首页',
            requiresAuth: false
        }
    },
    {
        path: '/lz/study/login',
        name: 'Login',
        component: Login,
        meta: {
            title: '登录',
            requiresAuth: false
        }
    },
    {
        path: '/lz/study/register',
        name: 'Register',
        component: Register,
        meta: {
            title: '注册',
            requiresAuth: false
        }
    },
    {
        path: '/oauth2/callback',
        name: 'OAuth2Callback',
        component: OAuth2Callback,
        meta: {
            title: 'OAuth2回调',
            requiresAuth: false
        }
    },
    {
        path: '/dynamicmenu',
        name: 'DynamicMenu',
        component: DynamicMenu,
        meta: {
            title: '管理菜单',
            requiresAuth: true,
        },
        children: [
            {
                path: 'user',
                name: 'UserManagement',
                component: () => import('../views/UserManagement.vue'),
                meta: {
                    title: '用户管理'
                }
            },
            {
                path: 'role',
                name: 'RoleManagement',
                component: () => import('../views/RoleManagement.vue'),
                meta: {
                    title: '角色管理'
                }
            },
            {
                path: 'permission',
                name: 'PermissionManagement',
                component: () => import('../views/PermissionManagement.vue'),
                meta: {
                    title: '权限管理'
                }
            },
            {
                path: 'article',
                name: 'ArticleManagement',
                component: () => import('../views/PermissionManagement.vue'),
                meta: {
                    title: '文章管理'
                }
            },
            {
                path: 'category',
                name: 'CategoryManagement',
                component: () => import('../views/CategoryManagement.vue'),
                meta: {
                    title: '分类管理'
                }
            },
            {
                path: 'visits',
                name: 'VisitsManagement',
                component: () => import('../views/VisitsManagement.vue'),
                meta: {
                    title: '访问统计'
                }
            },
            {
                path: 'analysis',
                name: 'AnalysisManagement',
                component: () => import('../views/AnalysisManagement.vue'),
                meta: {
                    title: '用户分析'
                }
            },
            {
                path: 'seedling-analysis',
                name: 'SeedlingAnalysis',
                component: () => import('../views/SeedlingDataAnalysis.vue'),
                meta: {
                    title: '育秧数据解析'
                }
            },
            {
                path: 'image-crawler',
                name: 'ImageCrawler',
                component: () => import('../views/dynamicmenu/ImageCrawler.vue'),
                meta: {
                    title: '图片采集'
                }
            },
            {
                path: 'image-list-crawler',
                name: 'ImageListCrawler',
                component: () => import('../views/dynamicmenu/ImageListCrawler.vue'),
                meta: {
                    title: '图片列表采集'
                }
            },
            {
                path: 'image-src-url',
                name: 'ImageSrcUrl',
                component: () => import('../views/dynamicmenu/ImageCrawlerManage.vue'),
                meta: {
                    title: '图片源网址管理'
                }
            },
            {
                path: 'image-crawler-detail',
                name: 'imageCrawler-detail',
                component: () => import('../views/dynamicmenu/CrawlRecordsDetail.vue'),
                meta: {
                    title: '图片源网址列表'
                }
            },
        ]
    },
    {
        path: '/entrust',
        name: 'entrust',
        component: DynamicMenu,
        meta: {
            title: '委托',
            requiresAuth: true,
        },
        children: [
            {
                path: 'list',
                name: 'EntrustList',
                component: () => import('../views/campus-entrust/EntrustList.vue'),
                meta: {
                    title: '首页'
                }
            },
            {
                path: 'publish',
                name: 'EntrustPublish',
                component: () => import('../views/campus-entrust/EntrustPublish.vue'),
                meta: {
                    title: '发布'
                }
            },
            {
                path: 'detail',
                name: 'EntrustDetail',
                component: () => import('../views/campus-entrust/EntrustDetail.vue'),
                meta: {
                    title: '详情'
                }
            },
            {
                path: 'profile',
                name: 'EntrustProfile',
                component: () => import('../views/campus-entrust/UserProfile.vue'),
                meta: {
                    title: '我的'
                }
            }
        ]
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes
})


// 常量定义
const LOGIN_PATH = '/lz/study/login'
const FORBIDDEN_PATH = '/lz/study/403'
const HOME_PATH = '/dynamicmenu'

const FORBIDDEN_CODE = 403
const NOT_FOUND_CODE = 404
const SERVER_ERROR_CODE = 500

// 转义HTML特殊字符
function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;")
}

router.beforeEach((to, from, next) => {
    const title = to.meta.title ? escapeHtml(to.meta.title) : ''
    document.title = title ? `${title} - 管理系统` : '管理系统'

    const userStore = useUserStore()

    if (to.meta.requiresAuth) {
        if (!userStore.isLogin) {
            next(LOGIN_PATH)
            ElMessage.error('请先登录')
            return
        }

        // 检查角色权限
        if (to.meta.roles) {
            const hasRole = to.meta.roles.some(role => userStore.hasRole(role))
            if (!hasRole) {
                ElMessage.error('无权限访问')
                next(FORBIDDEN_PATH)
                return
            }
        }
    }

    // 如果已登录且访问登录页，则重定向到首页
    if (to.path === LOGIN_PATH && userStore.isLogin) {
        ElMessage.info('已登录，请勿重复登录')
        next(HOME_PATH)
        return
    }

    next()
})


export default router 